import pandas as pd
from pathlib import Path
from datetime import datetime
from qfluentwidgets import (SettingCardGroup, StateToolTip, InfoBar, PushSettingCard,
                            InfoBarIcon, InfoBarPosition, ScrollArea, ExpandLayout)
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import InfoBar
from PySide6.QtCore import Qt, Signal, QThread
from PySide6.QtWidgets import QWidget, QFileDialog

from ..common.style_sheet import StyleSheet
from ..common.config import cfg
from ..utils.file_handing import FileHanding
from ..utils.file_tiding_thread import FileTidingThread
from .table_info import Information
from .keywords_card import KeywordsCard


class FileInterface(ScrollArea):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.scrollWidget = QWidget()
        self.expandLayout = ExpandLayout(self.scrollWidget)
        self.stateTooltip = None

        self.filePathGroup = SettingCardGroup("文件路径", self.scrollWidget)
        self.filePathCard = PushSettingCard(
            "选择文件路径", 
            FIF.FOLDER, 
            "拣货单", 
            cfg.get(cfg.filePath), 
            parent=self.filePathGroup
        )
        self.sourceFolderCard = PushSettingCard(
            "选择文件夹",
            FIF.FOLDER, 
            "源文件夹", 
            cfg.get(cfg.sourceFolder),
            parent=self.filePathGroup
        )
        self.targetFolderCard = PushSettingCard(
            "选择文件夹",
            FIF.FOLDER, 
            "目标文件夹", 
            cfg.get(cfg.targetFolder),
            parent=self.filePathGroup
        )

        self.fileTidingGroup = SettingCardGroup("文件处理", self.scrollWidget)
        self.getKeywordsCard = KeywordsCard(
            FIF.ZOOM, 
            "选择表格表头作为关键词", 
            parent=self.fileTidingGroup
        )
        self.fileTidingCard = PushSettingCard(
            "执行操作", 
            FIF.ZOOM, 
            "另存文件并改名",
            None, 
            parent=self.fileTidingGroup
        )

        self.infoTable = Information(self.scrollWidget)
        self.table_view()

        self.__initWidget()

    def __initWidget(self):
        self.resize(1000, 800)
        self.setMinimumSize(600, 440)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setViewportMargins(0, 20, 0, 20)
        self.setWidget(self.scrollWidget)
        self.setWidgetResizable(True)
        self.setObjectName('file_interface')

        self.scrollWidget.setObjectName("scrollWidget")
        
        StyleSheet.FILE_INTERFACE.apply(self)

        self.__initLayout()
        self.__connectSingalToSlot()

    def __initLayout(self):

        self.expandLayout.setSpacing(28)
        self.expandLayout.setContentsMargins(36, 10, 36, 0)
        
        self.filePathGroup.addSettingCard(self.filePathCard)
        self.filePathGroup.addSettingCard(self.sourceFolderCard)
        self.filePathGroup.addSettingCard(self.targetFolderCard)

        self.fileTidingGroup.addSettingCard(self.getKeywordsCard)
        self.fileTidingGroup.addSettingCard(self.fileTidingCard)
        
        self.expandLayout.addWidget(self.filePathGroup)
        self.expandLayout.addWidget(self.fileTidingGroup)
        self.expandLayout.addWidget(self.infoTable)

    def table_view(self):
        # 初始化
        filePath = cfg.get(cfg.filePath)
        self.current_time = datetime.now().strftime(r"%Y-%m-%d-%H-%M")
        self.getKeywordsCard.checked_list = []
        self.getKeywordsCard.choiceToggleButton.setChecked(False)
        
        if not filePath.lower().endswith(('.xlsx', '.pdf')):
            self.show_or_hide_tableview(False)
            return

        if not Path(filePath).exists():
            self.show_or_hide_tableview(False)
            return

        try:
            self.show_or_hide_tableview(True)

        except Exception as e:
            self.show_or_hide_tableview(False)
            print('e:', e)
            return
    
    def show_or_hide_tableview(self, is_show:bool):
        filePath = cfg.get(cfg.filePath)
        if is_show:
            self.info = FileHanding.read_file(filePath)
            self.infoTable.show()
        else:
            self.info = pd.DataFrame()
            self.infoTable.hide()
        self.infoTable.loadDataFrameToTableWidget(self.info)
        self.getKeywordsCard.addItems(self.info.columns)


    def refresh_view(self, df:pd.DataFrame):
        self.info = df
        # print('info:', self.info)
        self.infoTable.loadDataFrameToTableWidget(self.info)
        self.infoTable.show()

    def showStateInfo(self):
        if self.stateTooltip:
            self.stateTooltip.setContent('文件处理完成啦！')
            self.stateTooltip.setState(True)
            self.stateTooltip = None
        else:
            self.stateTooltip = StateToolTip('正在处理文件', '请耐心等待', self)
            # self.stateTooltip.move(510, 30)
            self.stateTooltip.move(self.stateTooltip.getSuitablePos())
            self.stateTooltip.show()

    def showNotFoundInfo(self, not_found_files):
        not_found_tip = InfoBar(
            icon=InfoBarIcon.WARNING,
            title='注意！',
            content='以下文件未找到：' + ', '.join(not_found_files),
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=-1,
            parent=self
        )
        not_found_tip.show()

    def showFileErrorInfo(self):
        InfoBar.warning(
            title='错误',
            content='文件有误，请重新选择文件',
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=2000,
            parent=self
        )

    def __onFilePathCardClicked(self):
        path = cfg.get(cfg.filePath)
        filePath, fileType = QFileDialog.getOpenFileName(self, "选择文件", path, "files(*.xlsx; *.pdf)")
        if not filePath or cfg.get(cfg.filePath) == filePath:
            return
        
        print('filePath:', filePath)
        cfg.set(cfg.filePath, filePath)
        self.filePathCard.setContent(filePath)

        self.table_view()

    def __onSourceFolderCardClicked(self):
        path = cfg.get(cfg.sourceFolder)
        sourceFolder = QFileDialog.getExistingDirectory(self, '选择文件夹', path)
        if not sourceFolder or cfg.get(cfg.sourceFolder) == sourceFolder:
            return
        
        print('targetFolder:', sourceFolder)
        cfg.set(cfg.sourceFolder, sourceFolder)
        self.sourceFolderCard.setContent(sourceFolder)

    def __onTargetFolderCardClicked(self):
        path = cfg.get(cfg.targetFolder)
        targetFolder = QFileDialog.getExistingDirectory(self, '选择文件夹', path)
        if not targetFolder or cfg.get(cfg.targetFolder) == targetFolder:
            return
        
        print('targetFolder:', targetFolder)
        cfg.set(cfg.targetFolder, targetFolder)
        self.targetFolderCard.setContent(targetFolder)

    def __onFileTidingCardClicked(self):        
        if self.info.empty:
            self.showFileErrorInfo()
            return
            
        self.fileTidingCard.setEnabled(False)
        self.getKeywordsCard.choiceToggleButton.setEnabled(False)
        try:
            src_dir = Path(cfg.get(cfg.sourceFolder))
            dst_dir = Path(cfg.get(cfg.targetFolder)) / self.current_time
            self.info = self.infoTable.readTableData()
            info_dict = {"src_dir": src_dir, "dst_dir": dst_dir, "df": self.info}
            self.thread_file_tiding = FileTidingThread(info_dict)
            self.thread_file_tiding._stateChangedSignal.connect(self.showStateInfo)
            self.thread_file_tiding._infoChangedSignal.connect(self.refresh_view)
            self.thread_file_tiding._finishedSignal.connect(self.__onFileTidingFinished)
            self.thread_file_tiding._notFoundSignal.connect(self.showNotFoundInfo)
            self.thread_file_tiding.start()
        except Exception as e:
            print('e:', e)
            self.fileTidingCard.setEnabled(True)
            self.getKeywordsCard.choiceToggleButton.setEnabled(True)

    def __onFileTidingFinished(self):
        self.fileTidingCard.setEnabled(True)
        self.getKeywordsCard.choiceToggleButton.setEnabled(True)

    def __onToggleButtonToggled(self, checked):
        if checked:
            self.info = self.info[self.getKeywordsCard.checked_list]
            # self.info = FileHanding.revise_value_of_df(self.info)
            # print('info:', self.info)
            # print('type(info):', type(self.info))

            self.info['处理状态'] = "未操作"
            self.infoTable.loadDataFrameToTableWidget(self.info)
        else:
            self.info = FileHanding.read_file(cfg.get(cfg.filePath))
            self.infoTable.loadDataFrameToTableWidget(self.info)

    def __connectSingalToSlot(self):
        self.filePathCard.clicked.connect(self.__onFilePathCardClicked)
        self.sourceFolderCard.clicked.connect(self.__onSourceFolderCardClicked)
        self.targetFolderCard.clicked.connect(self.__onTargetFolderCardClicked)
        
        self.fileTidingCard.clicked.connect(self.__onFileTidingCardClicked)
        self.getKeywordsCard.choiceToggleButton.toggled.connect(self.__onToggleButtonToggled)


